package sublinear.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import org.sqlite.SQLiteConfig;

public class DatabaseConnection {
	
	private static Map<String, Connection> dbMap = new HashMap<String, Connection>();
	
	private static final Logger log = Logger.getLogger( DatabaseConnection.class.getName() );
	
	static {
		try {
			Class.forName("org.sqlite.JDBC");
		} catch (ClassNotFoundException e) {
			// Could not find the JDBC class - just crash
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * Get a database connection for the provided JDBC
	 * 
	 * @param jdbcUrl
	 * @param readOnly Should the DB be open in read-only mode
	 * @return
	 * @throws Exception In case loading the SQLite DB connector failed
	 */
	public static final Connection getConnection(String dbName, boolean readOnly) {
		Connection db = dbMap.get(dbName + "_" + Boolean.toString(readOnly));
		if (db == null) {
			String jdbcUrl = "jdbc:sqlite:" + dbName + ".sqlite";
			try {			
				
				SQLiteConfig config = new SQLiteConfig();
				config.setReadOnly(readOnly); 
				
				db = DriverManager.getConnection(jdbcUrl, config.toProperties());
				dbMap.put(dbName + "_" + Boolean.toString(readOnly), db);
				
				log.info("Initialized DB with URL: " + jdbcUrl);
				
			} catch (SQLException e) {
				log.severe("Could not initialize DB with URL '" + jdbcUrl + "': " + e.getMessage() + 
						" SQL State: " + e.getSQLState());
				// Let it crash
				throw new RuntimeException(e);
			}
		}
		return db;
	}
	
}
